import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:rembercount/controller/countController.dart';
import 'package:rembercount/controller/authLoginController.dart';
import 'package:rembercount/controller/themeController.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:intl/intl.dart';
import 'category_detail_page.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui' as ui;
import 'package:bruno/bruno.dart';
import 'package:rembercount/services/export_service.dart';
import 'dart:io';
import 'dart:math' as math;


/// 企业级报表页面：专业设计风格，保留原有功能
class ReportPage extends StatefulWidget {
  const ReportPage({super.key});

  @override
  State<ReportPage> createState() => _ReportPageState();
}

class _ReportPageState extends State<ReportPage> {
  // 当前筛选条件
  String type = '支出'; // 支出/收入
  String period = '月'; // 周/月/年
  DateTime selectedDate = DateTime.now();

  // 所有账单数据
  List<Map<String, dynamic>> allRecords = [];
  bool loading = false;

  // 分段控制选项
  final List<String> typeOptions = ['支出', '收入'];
  final List<String> periodOptions = ['周', '月', '年'];

  final ThemeController themeController = Get.find<ThemeController>();
  final NumberFormat currencyFormat = NumberFormat.currency(symbol: '¥', decimalDigits: 2);
  final ExportService _exportService = ExportService();
  final GlobalKey _reportKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    _fetchRecords();
  }

  /// 请求后端获取账单数据
  Future<void> _fetchRecords() async {
    setState(() { loading = true; });
    final countController = Get.find<CountController>();
    final authController = Get.find<Authlogincontroller>();
    final email = authController.emailController.text;
    if (email.isEmpty) return;
    final records = await countController.getCount(email);
    setState(() {
      allRecords = List<Map<String, dynamic>>.from(records);
      loading = false;
    });
  }

  /// 获取预算数据
  Future<List<Map<String, dynamic>>> _getBudgetData() async {
    final authController = Get.find<Authlogincontroller>();
    final monthlyBudget = await authController.getPreFund();
    
    if (monthlyBudget <= 0) return [];
    
    List<Map<String, dynamic>> budgetData = [];
    
    if (period == '年') {
      // 年度：显示12个月的预算对比
      for (int month = 1; month <= 12; month++) {
        final monthDate = DateTime(selectedDate.year, month, 1);
        final daysInMonth = DateTime(selectedDate.year, month + 1, 0).day;
        final dailyBudget = monthlyBudget / daysInMonth;
        
        // 计算当月实际支出
        final actualAmount = allRecords.where((item) {
          if (item['countType'] != 'zhi') return false;
          final date = DateTime.tryParse(item['date'] ?? '') ?? DateTime.now();
          return date.year == selectedDate.year && date.month == month;
        }).fold<double>(0, (sum, item) {
          return sum + (double.tryParse(item['amount'].toString()) ?? 0);
        });
        
        budgetData.add({
          'name': '${month}月',
          'budget': monthlyBudget,
          'actual': actualAmount,
          'dailyBudget': dailyBudget,
        });
      }
    } else if (period == '月') {
      // 月度：显示每日的预算对比
      final daysInMonth = DateTime(selectedDate.year, selectedDate.month + 1, 0).day;
      final dailyBudget = monthlyBudget / daysInMonth;
      
      for (int day = 1; day <= daysInMonth; day++) {
        final dayDate = DateTime(selectedDate.year, selectedDate.month, day);
        
        // 计算当日实际支出
        final actualAmount = allRecords.where((item) {
          if (item['countType'] != 'zhi') return false;
          final date = DateTime.tryParse(item['date'] ?? '') ?? DateTime.now();
          return date.year == selectedDate.year && 
                 date.month == selectedDate.month && 
                 date.day == day;
        }).fold<double>(0, (sum, item) {
          return sum + (double.tryParse(item['amount'].toString()) ?? 0);
        });
        
        budgetData.add({
          'name': '${day}日',
          'budget': dailyBudget,
          'actual': actualAmount,
          'dailyBudget': dailyBudget,
        });
      }
    } else {
      // 周度：显示每日的预算对比
      final weekStart = selectedDate.subtract(Duration(days: selectedDate.weekday - 1));
      final dailyBudget = monthlyBudget / 30; // 按30天计算日预算
      
      for (int day = 0; day < 7; day++) {
        final dayDate = weekStart.add(Duration(days: day));
        
        // 计算当日实际支出
        final actualAmount = allRecords.where((item) {
          if (item['countType'] != 'zhi') return false;
          final date = DateTime.tryParse(item['date'] ?? '') ?? DateTime.now();
          return date.year == dayDate.year && 
                 date.month == dayDate.month && 
                 date.day == dayDate.day;
        }).fold<double>(0, (sum, item) {
          return sum + (double.tryParse(item['amount'].toString()) ?? 0);
        });
        
        budgetData.add({
          'name': '${dayDate.month}/${dayDate.day}',
          'budget': dailyBudget,
          'actual': actualAmount,
          'dailyBudget': dailyBudget,
        });
      }
    }
    
    return budgetData;
  }

  /// 根据当前筛选条件，聚合分类统计数据
  List<Map<String, dynamic>> get categoryStats {
    // 过滤出当前类型（支出/收入）和时间范围内的账单
    final filtered = allRecords.where((item) {
      if (item['countType'] == null) return false;
      final isType = (type == '支出' ? 'zhi' : 'shou') == item['countType'];
      if (!isType) return false;
      
      final date = DateTime.tryParse(item['date'] ?? '') ?? DateTime.now();
      if (period == '年') {
        return date.year == selectedDate.year;
      } else if (period == '月') {
        return date.year == selectedDate.year && date.month == selectedDate.month;
      } else {
        // 周：判断是否在本周
        final weekStart = selectedDate.subtract(Duration(days: selectedDate.weekday - 1));
        final weekEnd = weekStart.add(const Duration(days: 6));
        return !date.isBefore(weekStart) && !date.isAfter(weekEnd);
      }
    }).toList();
    
    // 按分类分组，统计金额和明细
    final Map<String, List<Map<String, dynamic>>> grouped = {};
    for (var item in filtered) {
      final cat = item['category'] ?? '未分类';
      if (!grouped.containsKey(cat)) {
        grouped[cat] = [];
      }
      grouped[cat]!.add(item);
    }
    
    // 生成统计数据
    final total = filtered.fold<double>(0, (sum, item) {
      final amount = double.tryParse(item['amount'].toString()) ?? 0;
      return sum + amount;
    });
    
    final List<Map<String, dynamic>> stats = [];
    grouped.forEach((cat, items) {
      final amount = items.fold<double>(0, (sum, item) {
        final itemAmount = double.tryParse(item['amount'].toString()) ?? 0;
        return sum + itemAmount;
      });
      
      stats.add({
        'name': cat,
        'amount': amount,
        'percent': total == 0 ? 0 : (amount / total * 100),
        'details': items,
      });
    });
    
    // 按金额降序排列
    stats.sort((a, b) => (b['amount'] as double).compareTo(a['amount'] as double));
    return stats;
  }

  /// 统计总金额
  double get totalAmount {
    return categoryStats.fold(0.0, (sum, c) => sum + (c['amount'] as double));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title: const Text('财务分析报表'),
        actions: [
          IconButton(
            icon: const Icon(Icons.more_vert),
            onPressed: () => _showExportOptions(),
          ),
        ],
      ),
      body: loading
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
              onRefresh: _fetchRecords,
              child: RepaintBoundary(
                key: _reportKey,
                child: Column(
                  children: [
                    // 专业筛选工具栏
                    _buildEnterpriseFilterBar(),
                    
                    // 核心数据展示区
                    Expanded(
                      child: ListView(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        children: [
                          // 财务概览卡片
                          // _buildFinancialOverview(),
                          //预算分析设置
                          _buildPreFundAnalysis(context),
                          // 分类分析图表
                          _buildCategoryAnalysis(),
                          
                          // 明细数据表格
                          _buildDataTable(),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
    );
  }
  // 获取关键点索引
  List<int> _getKeyIndexes(int len) {
    Set<int> idx = {0, len - 1};
    if (len > 2) idx.add(len ~/ 2);
    if (len > 4) {
      idx.add(len ~/ 4);
      idx.add((len * 3) ~/ 4);
    }
    return idx.toList()..sort();
  }

  // 只显示关键点的圆点和tip
  List<BrnPointData> _getBudgetPoints(List<Map<String, dynamic>> data, List<int> keyIndexes) {
    return data.asMap().entries.map((entry) {
      final index = entry.key;
      final d = entry.value;
      double value = (d['budget'] ?? 0) is num ? (d['budget'] ?? 0).toDouble() : double.tryParse(d['budget'].toString()) ?? 0;
      var formatValue = currencyFormat.format(value);
      return BrnPointData(
        pointText: '',
        x: index.toDouble(),
        y: value,
        lineTouchData: BrnLineTouchData(
          tipWindowSize: const Size(250, 40),
          onTouch: () => 
              '预算 ${d['name']} 金额: $formatValue'
              ,
        ),
      );
    }).toList();
  }
  List<BrnPointData> _getActualPoints(List<Map<String, dynamic>> data, List<int> keyIndexes) {
    return data.asMap().entries.map((entry) {
      final index = entry.key;
      final d = entry.value;
      double value = (d['actual'] ?? 0) is num ? (d['actual'] ?? 0).toDouble() : double.tryParse(d['actual'].toString()) ?? 0;
      var formatValue = currencyFormat.format(value);
      return BrnPointData(
        pointText: '',
        x: index.toDouble(),
        y: value,
        lineTouchData: BrnLineTouchData(
          tipWindowSize: const Size(250, 40),
          onTouch: () => 
              '实际 ${d['name']} 金额:$formatValue'
              ,
        ),
      );
    }).toList();
  }
  // X轴只显示关键点
  List<BrnDialItem> _getXDialValues(List<Map<String, dynamic>> data, List<int> keyIndexes) {
    return keyIndexes.map((index) => BrnDialItem(
      dialText: data[index]['name'],
      dialTextStyle: const TextStyle(fontSize: 12.0, color: Color(0xFF333333), fontWeight: FontWeight.bold),
      value: index.toDouble(),
    )).toList();
  }

  Widget _buildPreFundAnalysis(context) {
    return FutureBuilder<List<Map<String, dynamic>>>(
      future: _getBudgetData(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Container(
            margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.05),
                  spreadRadius: 1,
                  blurRadius: 8,
                ),
              ],
            ),
            child: const Center(child: CircularProgressIndicator()),
          );
        }
        if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return Container(
            margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.05),
                  spreadRadius: 1,
                  blurRadius: 8,
                ),
              ],
            ),
            child: const Center(
              child: Text(
                '请先设置月度预算',
                style: TextStyle(color: Colors.grey),
              ),
            ),
          );
        }
        final budgetData = snapshot.data!;
        final keyIndexes = _getKeyIndexes(budgetData.length);
        final authController = Get.find<Authlogincontroller>();
        return Container(
          margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          padding: const EdgeInsets.all(24),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.05),
                spreadRadius: 1,
                blurRadius: 8,
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '预算分析',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: themeController.themeColor.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      '预算对比',
                      style: TextStyle(
                        color: themeController.themeColor,
                        fontSize: 12,
                      ),
                    ),
                  ),
                ],
              ),
              FutureBuilder<double>(
                future: authController.getPreFund(),
                builder: (context, snap) {
                  if (snap.connectionState == ConnectionState.done && snap.hasData) {
                    return Padding(
                      padding: const EdgeInsets.only(top: 8, bottom: 4),
                      child: Text(
                        '当前月预算：¥${snap.data!.toStringAsFixed(2)}',
                        style: const TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w600,
                          color: Colors.blue,
                        ),
                      ),
                    );
                  } else {
                    return const SizedBox(height: 16);
                  }
                },
              ),
              const SizedBox(height: 8),
              Padding(
                padding: const EdgeInsets.only(left: 16, right: 16, top: 16, bottom: 0),
                child: SizedBox(
                  height: 300,
                  child: InteractiveViewer(
                    panEnabled: true,
                    scaleEnabled: false,
                    minScale: 1,
                    maxScale: 1,
                    child: SizedBox(
                      width: math.max(400, budgetData.length * 40),
                      height: 260,
                      child: BrnBrokenLine(
                        showPointDashLine: true,
                        yHintLineOffset: 20,
                        isTipWindowAutoDismiss: false,
                        lines: [
                          BrnPointsLine(
                            isShowPointText: true,
                            lineWidth: 3,
                            pointRadius: 5,
                            isShowPoint: true,
                            isCurve: true,
                            points: _getBudgetPoints(budgetData, keyIndexes),
                            lineColor: Colors.blue.withOpacity(0.8),
                          ),
                          BrnPointsLine(
                            isShowPointText: true,
                            lineWidth: 4,
                            pointRadius: 6,
                            isShowPoint: true,
                            isCurve: true,
                            points: _getActualPoints(budgetData, keyIndexes),
                            shaderColors: [Colors.red.withOpacity(0.4), Colors.red.withOpacity(0.05)],
                            lineColor: Colors.red.withOpacity(0.9),
                          ),
                        ],
                        size: Size(math.max(450, budgetData.length * 40), 260),
                        isShowXHintLine: true,
                        xDialValues: _getXDialValues(budgetData, keyIndexes),
                        xDialMin: 0,
                        xDialMax: budgetData.length.toDouble(),
                        yDialValues: _getYDialValues(budgetData),
                        yDialMin: _getMinValue(budgetData),
                        yDialMax: _getMaxValue(budgetData),
                        isHintLineSolid: false,
                        isShowYDialText: true,
                      ),
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 20),
              // 图例
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                decoration: BoxDecoration(
                  color: Colors.grey[50],
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.grey[200]!),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Row(
                      children: [
                        Container(
                          width: 16,
                          height: 4,
                          decoration: BoxDecoration(
                            color: Colors.blue.withOpacity(0.8),
                            borderRadius: BorderRadius.circular(2),
                          ),
                        ),
                        const SizedBox(width: 8),
                        const Text('预算', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                      ],
                    ),
                    const SizedBox(width: 32),
                    Row(
                      children: [
                        Container(
                          width: 16,
                          height: 4,
                          decoration: BoxDecoration(
                            color: Colors.red.withOpacity(0.9),
                            borderRadius: BorderRadius.circular(2),
                          ),
                        ),
                        const SizedBox(width: 8),
                        const Text('实际支出', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  List<BrnDialItem> _getYDialValues(List<Map<String, dynamic>> budgetData) {
    double min = _getMinValue(budgetData);
    double max = _getMaxValue(budgetData);
    
    // 确保有合理的范围
    if (max == min) {
      max = min + 1000; // 如果最大值等于最小值，给一个合理的范围
    }
    
    double dValue = (max - min) / 4; // 减少刻度数量，让显示更清晰
    List<BrnDialItem> yDialValue = [];
    for (int index = 0; index <= 4; index++) {
      final value = min + index * dValue;
      yDialValue.add(BrnDialItem(
        dialText: currencyFormat.format(value),
        dialTextStyle: const TextStyle(fontSize: 11.0, color: Color(0xFF666666), fontWeight: FontWeight.w500),
        value: value,
      ));
    }
    return yDialValue;
  }

  double _getMinValue(List<Map<String, dynamic>> budgetData) {
    if (budgetData.isEmpty) return 0;
    double minValue = budgetData[0]['budget'];
    for (Map<String, dynamic> data in budgetData) {
      minValue = math.min(minValue, math.min(data['budget'], data['actual']));
    }
    return minValue;
  }

  double _getMaxValue(List<Map<String, dynamic>> budgetData) {
    if (budgetData.isEmpty) return 0;
    double maxValue = budgetData[0]['budget'];
    for (Map<String, dynamic> data in budgetData) {
      maxValue = math.max(maxValue, math.max(data['budget'], data['actual']));
    }
    return maxValue;
  }

  Widget _buildEnterpriseFilterBar() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.08),
            spreadRadius: 0,
            blurRadius: 12,
          ),
        ],
      ),
      child: Column(
        children: [
          // 类型选择
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: typeOptions.map((option) {
              final isSelected = type == option;
              return Padding(
                padding: const EdgeInsets.symmetric(horizontal: 4),
                child: ElevatedButton(
                  onPressed: () {
                    if (!isSelected) {
                      setState(() => type = option);
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: isSelected ? themeController.themeColor : Colors.white,
                    foregroundColor: isSelected ? Colors.white : Colors.black87,
                  ),
                  child: Text(option),
                ),
              );
            }).toList(),
          ),
          
          const SizedBox(height: 12),
          
          // 时间选择
          Row(
            children: [
              Expanded(
                child: OutlinedButton(
                  onPressed: _showPeriodPicker,
                  style: OutlinedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                  ),
                  child: FittedBox(
                    fit: BoxFit.scaleDown,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(period),
                        const Icon(Icons.arrow_drop_down, size: 16),
                      ],
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Flexible(
                child: OutlinedButton(
                  onPressed: _showDatePicker,
                  style: OutlinedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                  ),
                  child: FittedBox(
                    fit: BoxFit.scaleDown,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Icon(Icons.calendar_today, size: 16),
                        const SizedBox(width: 4),
                        Text(_getDateLabel()),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildFinancialOverview() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.05),
            spreadRadius: 1,
            blurRadius: 8,
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //   children: [
          //     // Text(
          //     //   '${period}财务总览',
          //     //   style: const TextStyle(
          //     //     fontSize: 16,
          //     //     color: Colors.grey,
          //     //   ),
          //     // ),
          //     Container(
          //       padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          //       decoration: BoxDecoration(
          //         color: type == '支出' 
          //           ? Colors.red.withOpacity(0.1) 
          //           : Colors.green.withOpacity(0.1),
          //         borderRadius: BorderRadius.circular(4),
          //       ),
          //       child: Text(
          //         type,
          //         style: TextStyle(
          //           color: type == '支出' ? Colors.red : Colors.green,
          //           fontSize: 12,
          //         ),
          //       ),
          //     ),
          //   ],
          // ),
          const SizedBox(height: 16),
          RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: '¥',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.w500,
                    color: type == '支出' ? Colors.red : Colors.green,
                  ),
                ),
                TextSpan(
                  text: currencyFormat.format(totalAmount),
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: type == '支出' ? Colors.red : Colors.green,
                    fontFamily: 'Montserrat',
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),
          // 趋势分析微型图表
          _buildMiniTrendChart(),
        ],
      ),
    );
  }

  Widget _buildMiniTrendChart() {
    // 获取最近7天的数据
    final List<double> dailyAmounts = List.generate(7, (index) {
      final date = DateTime.now().subtract(Duration(days: 6 - index));
      return allRecords.where((record) {
        if (record['countType'] != (type == '支出' ? 'zhi' : 'shou')) return false;
        final recordDate = DateTime.tryParse(record['date'] ?? '') ?? DateTime.now();
        return recordDate.year == date.year && 
               recordDate.month == date.month && 
               recordDate.day == date.day;
      }).fold<double>(0, (sum, record) {
        return sum + (double.tryParse(record['amount'].toString()) ?? 0);
      });
    });

    // 计算最大值用于缩放
    final maxAmount = dailyAmounts.isEmpty ? 1.0 : dailyAmounts.reduce((a, b) => a > b ? a : b);

    return Container(
      height: 40,
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: List.generate(7, (index) {
          final height = maxAmount == 0 ? 0.0 : (dailyAmounts[index] / maxAmount * 30);
          return Container(
            width: 8,
            height: height,
            decoration: BoxDecoration(
              color: themeController.themeColor,
              borderRadius: BorderRadius.circular(2),
            ),
          );
        }),
      ),
    );
  }

  Widget _buildCategoryAnalysis() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.05),
            spreadRadius: 1,
            blurRadius: 8,
          ),
        ],
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '分类分析',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: themeController.themeColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  '占比分析',
                  style: TextStyle(
                    color: themeController.themeColor,
                    fontSize: 12,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 24),
          SizedBox(
            height: 240,
            child: Row(
              children: [
                // 饼图
                Expanded(
                  child: CustomPaint(
                    painter: _EnterprisePieChartPainter(categoryStats),
                  ),
                ),
                // 图例
                Expanded(
                  child: ListView.builder(
                    itemCount: categoryStats.length,
                    itemBuilder: (context, index) {
                      final cat = categoryStats[index];
                      return Padding(
                        padding: const EdgeInsets.only(bottom: 12),
                        child: Row(
                          children: [
                            Container(
                              width: 12,
                              height: 12,
                              decoration: BoxDecoration(
                                color: _getCategoryColor(cat['name']),
                                borderRadius: BorderRadius.circular(4),
                              ),
                            ),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                cat['name'],
                                style: const TextStyle(fontSize: 14),
                              ),
                            ),
                            Text(
                              '${cat['percent'].toStringAsFixed(1)}%',
                              style: const TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDataTable() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.05),
            spreadRadius: 1,
            blurRadius: 8,
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(24, 24, 24, 16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '分类明细',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.settings, size: 18),
                  onPressed: () {},
                ),
              ],
            ),
          ),
          if (categoryStats.isEmpty)
            const Padding(
              padding: EdgeInsets.symmetric(vertical: 32),
              child: Center(child: Text('暂无数据')),
            )
          else
            ListView.separated(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: categoryStats.length,
              separatorBuilder: (context, index) => const Divider(height: 1),
              itemBuilder: (context, index) {
                final cat = categoryStats[index];
                return ListTile(
                  contentPadding: const EdgeInsets.symmetric(horizontal: 24),
                  leading: Container(
                    width: 36,
                    height: 36,
                    decoration: BoxDecoration(
                      color: _getCategoryColor(cat['name']).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: Center(
                      child: Text(
                        cat['name'].toString().substring(0, 1),
                        style: TextStyle(
                          color: _getCategoryColor(cat['name']),
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                  title: Text(cat['name']),
                  subtitle: LinearProgressIndicator(
                    value: cat['percent'] / 100,
                    backgroundColor: Colors.grey[200],
                    color: _getCategoryColor(cat['name']),
                    minHeight: 4,
                  ),
                  trailing: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        currencyFormat.format(cat['amount']),
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: type == '支出' ? Colors.red : Colors.green,
                          fontFamily: 'Montserrat',
                        ),
                      ),
                      Text(
                        '${cat['percent'].toStringAsFixed(1)}%',
                        style: const TextStyle(
                          color: Colors.grey,
                          fontSize: 12,
                        ),
                      ),
                    ],
                  ),
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (_) => CategoryDetailPage(
                          categoryName: cat['name'],
                          allRecords: cat['details'],
                        ),
                      ),
                    );
                  },
                );
              },
            ),
        ],
      ),
    );
  }

  Color _getCategoryColor(String category) {
    final colors = [
      Colors.blue,
      Colors.orange,
      Colors.green,
      Colors.purple,
      Colors.red,
      Colors.amber,
      Colors.teal,
      Colors.indigo,
    ];
    return colors[category.hashCode % colors.length];
  }

  /// 获取顶部日期标签（中文）
  String _getDateLabel() {
    if (period == '年') return '${selectedDate.year}年';
    if (period == '月') return '${selectedDate.year}年${selectedDate.month.toString().padLeft(2, '0')}月';
    // 周：显示本周的起止日期
    final weekStart = selectedDate.subtract(Duration(days: selectedDate.weekday - 1));
    final weekEnd = weekStart.add(const Duration(days: 6));
    return '${weekStart.month}月${weekStart.day}日 - ${weekEnd.month}月${weekEnd.day}日';
  }

  /// 底部弹框选择年/月/周
  void _showPeriodPicker() async {
    await showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) {
        return Container(
          padding: const EdgeInsets.symmetric(vertical: 20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 40,
                height: 4,
                margin: const EdgeInsets.only(bottom: 20),
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              Text(
                '选择统计周期',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: themeController.themeColor,
                ),
              ),
              const SizedBox(height: 20),
              ...periodOptions.map((e) => InkWell(
                onTap: () {
                  setState(() { period = e; });
                  Navigator.pop(context);
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
                  decoration: BoxDecoration(
                    color: period == e ? themeController.themeColor.withOpacity(0.1) : null,
                    border: Border(
                      bottom: BorderSide(
                        color: Colors.grey[200]!,
                        width: 0.5,
                      ),
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        e,
                        style: TextStyle(
                          fontSize: 16,
                          color: period == e ? themeController.themeColor : Colors.black87,
                          fontWeight: period == e ? FontWeight.bold : FontWeight.normal,
                        ),
                      ),
                      if (period == e)
                        Icon(
                          Icons.check_circle,
                          color: themeController.themeColor,
                          size: 20,
                        ),
                    ],
                  ),
                ),
              )).toList(),
            ],
          ),
        );
      },
    );
  }

  /// 日期选择器
  void _showDatePicker() async {
    DateTime? picked;
    await showModalBottomSheet<DateTime>(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) {
        return Container(
          padding: const EdgeInsets.symmetric(vertical: 20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 40,
                height: 4,
                margin: const EdgeInsets.only(bottom: 20),
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              Text(
                period == '年' ? '选择年份' : period == '月' ? '选择年月' : '选择日期',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: themeController.themeColor,
                ),
              ),
              const SizedBox(height: 20),
              if (period == '年')
                SizedBox(
                  height: 300,
                  child: YearPicker(
                    firstDate: DateTime(2000),
                    lastDate: DateTime(2100),
                    selectedDate: selectedDate,
                    onChanged: (date) {
                      Navigator.pop(context, date);
                    },
                  ),
                )
              else if (period == '月')
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 24),
                  child: Column(
                    children: [
                      BrnCalendarView(
                        selectMode: SelectMode.single,
                        displayMode:DisplayMode.month,
                        dateChange: (date) {
                          // 只保留年月，将日期设为1号
                          final newDate = DateTime(date.year, date.month, 1);
                          Navigator.pop(context, newDate);
                        },
                      )
                    ],
                  ),
                )
              else
                Container(
                  height: 300,
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: CalendarDatePicker(
                    initialDate: selectedDate,
                    firstDate: DateTime(2000),
                    lastDate: DateTime(2100),
                    onDateChanged: (date) {
                      Navigator.pop(context, date);
                    },
                  ),
                ),
            ],
          ),
        );
      },
    ).then((date) {
      if (date != null) {
        setState(() { selectedDate = date; });
      }
    });
  }
 
  /// 导出选项弹窗
  void _showExportOptions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text(
              '导出报表',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 24),
            ListTile(
              leading: const Icon(Icons.picture_as_pdf, color: Colors.red),
              title: const Text('PDF格式'),
              onTap: () {
                Navigator.pop(context);
                _exportToPDF();
              },
            ),
            ListTile(
              leading: const Icon(Icons.table_chart, color: Colors.green),
              title: const Text('Excel格式'),
              onTap: () {
                Navigator.pop(context);
                _exportToExcel();
              },
            ),
            ListTile(
              leading: const Icon(Icons.image, color: Colors.blue),
              title: const Text('图像格式'),
              onTap: () {
                Navigator.pop(context);
                _exportAsImage();
              },
            ),
          ],
        ),
      ),
    );
  }

  void _exportToPDF() async {
    final path = await _exportService.exportToPDF(categoryStats, type, period);
    if (path != null) {
      Get.snackbar('导出成功', 'PDF文件已保存至: $path');
    }
  }

  void _exportToExcel() async {
    final path = await _exportService.exportToExcel(categoryStats, type, period);
    if (path != null) {
      Get.snackbar('导出成功', 'Excel文件已保存至: $path');
    }
  }

  void _exportAsImage() async {
    try {
      

      final RenderRepaintBoundary boundary = _reportKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      final image = await boundary.toImage(pixelRatio: 3.0);
      final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      final bytes = byteData!.buffer.asUint8List();

      final exportDir = await _exportService.getExportDirectory();
      final fileName = '${type}_${period}_${DateTime.now().millisecondsSinceEpoch}.png';
      final file = File('$exportDir/$fileName');
      await file.writeAsBytes(bytes);

      Get.snackbar('导出成功', '图片已保存至: ${file.path}');
    } catch (e) {
      Get.snackbar('错误', '导出图片失败: $e');
    }
  }
}

/// 企业级饼图绘制器
class _EnterprisePieChartPainter extends CustomPainter {
  final List<Map<String, dynamic>> categories;
  _EnterprisePieChartPainter(this.categories);

  @override
  void paint(Canvas canvas, Size size) {
    if (categories.isEmpty) return;

    double startRadian = -3.14 / 2;
    final radius = size.width / 2.5;
    final center = Offset(size.width / 2, size.height / 2);
    
    // 绘制中心圆
    final centerPaint = Paint()
      ..color = Colors.blue[50]!;
    canvas.drawCircle(center, radius * 0.3, centerPaint);
    
    // 绘制中心文字
    final textStyle = TextStyle(
      color: Colors.blue[800],
      fontWeight: FontWeight.bold,
      fontSize: 16,
    );
    final textSpan = TextSpan(
      text: 'FIN',
      style: textStyle,
    );
    final textPainter = TextPainter(
      text: textSpan,
      textDirection: ui.TextDirection.ltr,
    );
    textPainter.layout();
    textPainter.paint(
      canvas,
      Offset(center.dx - textPainter.width / 2, center.dy - textPainter.height / 2),
    );
    
    // 绘制饼图
    final paint = Paint()
      ..style = PaintingStyle.fill;
    final colors = [
      Colors.blue,
      Colors.orange,
      Colors.green,
      Colors.purple,
      Colors.red,
      Colors.amber,
      Colors.teal,
      Colors.indigo,
    ];
    
    // 计算总百分比
    final totalPercent = categories.fold<double>(0, (sum, cat) => sum + (cat['percent'] as double));
    
    for (int i = 0; i < categories.length; i++) {
      final cat = categories[i];
      final percent = cat['percent'] as double;
      if (percent <= 0) continue;
      
      final sweepRadian = 3.14 * 2 * (percent / totalPercent);
      
      // 创建渐变效果
      final gradient = SweepGradient(
        startAngle: startRadian,
        endAngle: startRadian + sweepRadian,
        colors: [
          colors[i % colors.length].withOpacity(0.8),
          colors[i % colors.length].withOpacity(0.4),
        ],
      );
      
      paint.shader = gradient.createShader(
        Rect.fromCircle(center: center, radius: radius),
      );
      
      // 绘制扇形
      canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        startRadian,
        sweepRadian,
        true,
        paint,
      );
      
      // 绘制边框
      final borderPaint = Paint()
        ..style = PaintingStyle.stroke
        ..color = Colors.white
        ..strokeWidth = 2;
      canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        startRadian,
        sweepRadian,
        true,
        borderPaint,
      );
      
      startRadian += sweepRadian;
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}